package cd.safe.school.activity;

import org.androidpn.client.Constants;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;
import cd.safe.school.R;
import cd.safe.school.data.AppData;
import cd.safe.school.ui.MyDialog;
import cd.safe.school.util.NetWorkUtil;
import cd.safe.school.util.Parse;
import cd.safe.school.util.SharedPreUtil;
import cd.safe.school.util.User;

public class LoginActivity extends Activity implements OnClickListener {
	// 登录按钮
	private Button login;
	// 登录用户名
	private EditText login_name;
	// 登录密码
	private EditText login_password;
	// 是否记住密码
	private CheckBox remember;
	// 是否自动登录
	private CheckBox autologin;
	private boolean tag = false;
	private MyDialog dialog;
	private String username;
	private String password;
	private AppData ad = new AppData(this);
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// if (dialog.isShowing())
			// dialog.dismiss();
			if (tag) {
				switch (msg.what) {
				// 登录失败
				case -1:
					tag = false;
					break;
				// 登录成功
				case 1:
					// ...........存储用户信息
					SQLiteDatabase db = ad.getWritableDatabase();
					ContentValues values = new ContentValues();
					values.put("userID", User.userID);
					values.put("action", User.action);
					values.put("phone", User.phone);
					db.insert("User", "userID", values);
					db.close();
					// ...................

					Intent intent = new Intent(LoginActivity.this,
							HomeActivity.class);
					intent.putExtra("username", username);
					intent.putExtra("password", password);
					intent.putExtra("userId", User.userID);

					SharedPreferences sharedPrefs = getSharedPreferences(
							Constants.SHARED_PREFERENCE_NAME,
							Context.MODE_PRIVATE);
					Editor editor = sharedPrefs.edit();
					editor.putString(Constants.XMPP_USERNAME, username);
					editor.putString(Constants.XMPP_PASSWORD, password);
					editor.commit();
					startActivity(intent);
					finish();
					break;

				default:
					break;
				}
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		SharedPreUtil.addActivity(this);
		Button title_fanhui = (Button) findViewById(R.id.title_fanhui);
		Button title_butn = (Button) findViewById(R.id.title_butn);
		title_butn.setVisibility(View.GONE);
		title_fanhui.setVisibility(View.GONE);

		login = (Button) findViewById(R.id.login);

		login_name = (EditText) findViewById(R.id.login_name);
		login_password = (EditText) findViewById(R.id.login_password);
		remember = (CheckBox) findViewById(R.id.remember);
		autologin = (CheckBox) findViewById(R.id.autologin);
		// --------------------------------------------
		// 获取IMEI码
		// TelephonyManager manager = (TelephonyManager) this
		// .getSystemService(TELEPHONY_SERVICE);
		// ---------------------------------------------

		TelephonyManager manager = (TelephonyManager) LoginActivity.this
				.getSystemService(TELEPHONY_SERVICE);
		String phoneNumber = manager.getLine1Number();

		phoneNumber = "13700620166";
		if (phoneNumber != null && !"".equals(phoneNumber)) {
			int code = Parse.parselogin(phoneNumber);
			if (code == -100) {
				Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
				phoneNumber = null;
			} else {
				tag = true;
				Message msg = new Message();
				msg.what = 1;
				handler.sendMessage(msg);

			}

		}
		if ("".equals(phoneNumber) || phoneNumber == null) {

			if (SharedPreUtil.getValue(LoginActivity.this, "auto", "false")
					.equals("true")) {// 如果自动登录状态为真，则设置对应的选择框为选中状态，并登录
				remember.setChecked(true);
				autologin.setChecked(true);
				login_name.setText(SharedPreUtil.getValue(LoginActivity.this,
						"username", "aagh5P"));
				login_password.setText(SharedPreUtil.getValue(
						LoginActivity.this, "password", "2w2w2w2w"));

				login();
			}
			if (SharedPreUtil.getValue(LoginActivity.this, "remember", "false")
					.equals("true")) {// 如果只是记住密码状态，则将用户名密码恢复到输入框中，并更新对应的选择框状态
				remember.setChecked(true);
				login_name.setText(SharedPreUtil.getValue(LoginActivity.this,
						"username", "aagh5P"));
				login_password.setText(SharedPreUtil.getValue(
						LoginActivity.this, "password", "2w2w2w2w"));
				updateSelection();
			}

			remember.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					if (!isChecked) {
						autologin.setChecked(false);
					}

				}
			});
			autologin.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					if (isChecked) {
						remember.setChecked(true);
					}

				}
			});

			login.setOnClickListener(this);

		}
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login:
			login();
			break;

		default:
			break;
		}

	}

	private void login() {
		tag = true;
		if (NetWorkUtil.NetworkStateCheck(LoginActivity.this)) {
			if (login_name.length() > 0 && login_password.length() > 0) {
				dialog = new MyDialog(LoginActivity.this, handler);
				dialog.setMessage("登录中。。。");
				dialog.setCancelable(true);
				dialog.show();
				// 模拟登录验证代码。。。

				// -------------------------------
				username = login_name.getText().toString();
				password = login_password.getText().toString();
				new Thread(new Runnable() {

					@Override
					public void run() {
						// -----------------------------------

						// ---------------------------------
						if (remember.isChecked() && !autologin.isChecked()) {
							// 用户只选择了记住密码,则需要更新SharedPreference中的相关配置，以便下次登录的时候恢复输入
							SharedPreUtil.putValue(LoginActivity.this,
									"remember", "true");
							SharedPreUtil.putValue(LoginActivity.this, "auto",
									"false");
							SharedPreUtil
									.putValue(LoginActivity.this, "username",
											login_name.getText().toString());
							SharedPreUtil.putValue(LoginActivity.this,
									"password", login_password.getText()
											.toString());
						} else if (autologin.isChecked()) {
							// 如果用户选择了自动登录，则不仅要在下次登录的时候恢复工号和密码，还得自动登录
							SharedPreUtil.putValue(LoginActivity.this, "auto",
									"true");
							SharedPreUtil
									.putValue(LoginActivity.this, "username",
											login_name.getText().toString());
							SharedPreUtil.putValue(LoginActivity.this,
									"password", login_password.getText()
											.toString());
						} else {
							SharedPreUtil.putValue(LoginActivity.this,
									"remember", "false");
							SharedPreUtil.putValue(LoginActivity.this, "auto",
									"false");
						}
						// -------------------------------------------
						Message msg = new Message();
						msg.what = 1;
						handler.sendMessage(msg);

					}
				}).start();

			} else if (login_name.length() == 0 && login_password.length() > 0) {
				Toast.makeText(LoginActivity.this, "用户名不能为空",
						Toast.LENGTH_SHORT).show();

			} else if (login_name.length() > 0 && login_password.length() == 0) {
				Toast.makeText(LoginActivity.this, "密码不能为空", Toast.LENGTH_SHORT)
						.show();

			} else if (login_name.length() == 0 && login_password.length() == 0) {
				Toast.makeText(LoginActivity.this, "请输入用户名和密码登录",
						Toast.LENGTH_SHORT).show();

			}

		} else {
			Toast.makeText(LoginActivity.this, "当前网络不可用", Toast.LENGTH_SHORT)
					.show();

		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			new AlertDialog.Builder(LoginActivity.this)
					.setMessage("确认要退出吗?")
					.setTitle("提示")
					.setNegativeButton("取消", null)
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
									finish();

								}
							}).show();
		}
		return super.onKeyDown(keyCode, event);
	}

	private void updateSelection() {
		login_name.setSelection(login_name.getText().toString().length());
		login_password.setSelection(login_password.getText().toString()
				.length());
	}
}
